<template>
  <div class="index-box" ref="index">
    <el-row :gutter="10" style="height:100%;margin:0px">
      <el-col :span="24">
        <div class="table-box" >
          <div class="actionBtn" ref="activeBox" style="margin-bottom: 10px;">
            <div class="actionBtnLeft">
             <!-- <el-button type="primary" @click="handleAdd" size="small" icon="el-icon-add">新增商品分类</el-button> -->
            </div>
            <div class="actionBtnRight">
                <MyRefresh/>
            </div>
          </div>
          <div class="table" ref="table" >
            <el-table  :data="dataList" style="width: 100%;"  border :height="tableHeight" id="crTable"   :key="tableKey"  row-key="categoryId" :tree-props="treeProps">
              <!-- <el-table-column type="selection" width="55" ></el-table-column> -->
              <el-table-column prop="name" label="分类名称" ></el-table-column>
              <el-table-column prop="sortOrder" label="排序" ></el-table-column>
              <el-table-column label="状态" align="center" >
                <template slot-scope="scope">
                 <MySwitch :value.sync="scope.row.status" :id="scope.row.status" text="显示|隐藏" textValue="1|2" @changeStatus="handleStatusChange(scope.row)" style="display: flex;justify-content: center;"></MySwitch>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="操作" width="150">
                 <template #default="scope">
                 		<el-button
                      size="medium"
                      type="text"
                      icon="el-icon-edit"
                      @click="handleEdit(scope.row)"
                    >修改排序</el-button>
                    <!--<el-button
                      size="medium"
                      type="text"
                      icon="el-icon-rank"
                      @click="handleEdit(scope.row)"
                    >拖动滑动</el-button>-->
                   <!-- <el-button
                      size="medium"
                      type="text"
                      icon="el-icon-edit"
                      @click="handleEdit(scope.row)"
                    >修改</el-button>
                    <el-button
                      v-if="!scope.row.children.length"
                      size="medium"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleDelt(scope.row)"
                    >删除</el-button> -->
                 </template>
              </el-table-column>
            </el-table>
          </div>


          <!-- /*修改排序*/	 -->
          <el-dialog :title="dialogTitle" width="400px" v-dialogDrag :close-on-click-modal="false" :visible.sync="shopClassifyVisible" @close="shopClassifyVisible = false">
              <el-form class="formDialog"  label-position="right" :model="user"  :rules="rules" ref="user" >
                	<el-form-item label="排序:" prop="sortOrder"  label-width="85px" style="width:100%">
                   	<el-input-number v-model="user.sortOrder"  :min="1"  style="width:100%"></el-input-number>
                	</el-form-item>
              </el-form>
             <div slot="footer" class="dialog-footer">
               <el-button @click="shopClassifyVisible = false" size="small">取 消</el-button>
               <el-button type="primary" @click="editSortSubmit('user')" size="small" :loading="userLoading">确 定</el-button>
             </div>
           </el-dialog>

        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import {  goodsCategoryList, goodsUpdateCategory, goodsCategoryAdd, goodsCategoryDelete, goodsCategoryUpdateStatus  } from '@/api/getData';
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import Sortable from 'sortablejs'
  export default {
    components: { Treeselect },
    data() {
      return {
        loading: false,
        userLoading: false,
        treeProps:{children: 'children'},
        searchForm: {
          tagName: undefined,
          typeId :'',
          pageNum:1,
          pageSize:20,
        },
        treeList: [],
        tableHeight:0,//table 高度
        dataList:[],
        total: 0,
        multipleSelection: '',

        shopClassifyVisible:false,
        dialogTitle:'',
        user: {
          categoryId:'',
          sortOrder:''
        },
        rules: {
          sortOrder: [{required: true, message: '排序不能为空',trigger: 'blur'}],
        },
         tableKey:'1',
         index1:0,
         index2:0,
      }
    },
    mounted() {
      //this.dataInfo();
      //this.rowDrop()
      this.dataInfo();
      this.$nextTick(() => {
          this.tableHeight = this.$refs.index.offsetHeight  - 80;
      })
    },
    methods: {
      //行拖拽
      rowDrop() {
        const tbody = document.getElementById("crTable").querySelector('.el-table__body-wrapper tbody');
        const _this = this;
        let status = true;
        Sortable.create(tbody, {
          animation: 300,
          onMove ({ dragged, related }) {
            let arr = _this.forArr(dragged.rowIndex,related.rowIndex);
            console.log(arr);
            status = true;
            if (arr[0].parentId != arr[1].parentId) { //不能跨级拖拽
              status = false;
              return false
            }
          },
          onEnd({ newIndex, oldIndex }) {
            if(status){
              console.log('yse');
              let data = _this.forArr(newIndex, oldIndex);
              let index0 = data[0].sortOrder;
              let index1 = data[1].sortOrder;
               data[0].sortOrder = index1;
               data[1].sortOrder = index0;
              goodsUpdateCategory(data).then((result) => {
                if (result.code == 200) {
                  _this.$message.success(result.msg);
                  _this.dataInfo();
                } else {
                  _this.$message.error(result.msg);
                }
              });
            }
            console.log(newIndex, oldIndex);

          }
        })
      },
      forArr(draggedIndex, relatedIndex){
          let draggedRow;
          let relatedRow;
          let data = this.dataList;
          let index = 0;
          for(let i=0;i<data.length;i++){
              data[i].index = index;
              if(index==draggedIndex){
                draggedRow = data[i];
              }
              if(index==relatedIndex){
                relatedRow = data[i];
              }
              index++;
              if(data[i].children){
                for(let a=0;a<data[i].children.length;a++){
                   data[i].children[a].index = index;
                  if(index==draggedIndex){
                    draggedRow = data[i].children[a];
                  }
                  if(index==relatedIndex){
                    relatedRow = data[i].children[a];
                  }
                   index++;
                  if(data[i].children[a].children){
                    for(let b=0;b<data[i].children[a].children.length;b++){
                      data[i].children[a].children[b].index = index;
                      if(index==draggedIndex){
                        draggedRow = data[i].children[a].children[b];
                      }
                      if(index==relatedIndex){
                        relatedRow = data[i].children[a].children[b];
                      }
                       index++;
                    }
                  }
                }
              }
          }
        return [draggedRow,relatedRow]
      },
      handleAdd(){
        this.resetForm("user");
        this.categoryId = '';
        this.dialogTitle = '新增商品分类';
        this.shopClassifyVisible = true;
      },
      // 角色状态修改
      handleStatusChange(row) {
        let text = row.status === "1" ? "显示" : "隐藏";
        this.$modal.confirm(`确认要${text}${row.categoryName}分类吗？`).then(function() {
          return goodsCategoryUpdateStatus({categoryId:row.categoryId , 'status':row.status});
        }).then((res) => {
          if(res.code == 200){
            this.$modal.msgSuccess(res.msg);
          }else{
            row.status = row.status === "1" ? "2" : "1";
            this.$modal.msgError(res.msg);
          }
        }).catch(function() {
          row.status = row.status === "1" ? "2" : "1";
        });
      },
      handleEdit(row){
        this.user.sortOrder = row.sortOrder;
        this.user.categoryId = row.categoryId;
        this.dialogTitle = `修改分类名称为${row.categoryName}的排序`;
        this.shopClassifyVisible = true;
      },
      /** 转换部门数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.categoryId,
          label: node.categoryName,
          children: node.children
        };
      },
      editSortSubmit(formName) {/*修改排序*/
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.userLoading = true;
            goodsCategoryAdd(this.user).then((result) => {
              if (result.code == 200) {
                this.$message.success(result.msg);
                this.shopClassifyVisible = false;
                this.dataInfo();
              } else {
                this.$message.error(result.msg);
              }
              this.userLoading = false;
            });
          }
        })
      },
      async updateCategory(list){
        try {
          const result = await goodsUpdateCategory();
          if (result.code == 200) {
             this.$modal.msgSuccess('拖动成功');
          } else {
             this.$modal.msgError(result.msg);
          }
        } catch (err) {
          console.log(err)
        }
      },
      set1(){
         this.dataList = this.copyDataList;
         console.log(this.dataList)
      },
      async dataInfo() {
        try {
          this.loading = true;
          this.dataList = [];
          const result = await goodsCategoryList({type:1});

          if (result.code == 200) {
            this.dataList = result.data;
            this.majorRowData = result.data;
          } else {
            this.$message.error(result.msg);
          }
          this.loading = false;
        } catch (err) {
          this.loading = false;
          console.log(err)
        }
      },

      handleSearch() {
        this.searchForm.page = 1;
        this.dataInfo();
      },

    }
  }
</script>

<style scoped lang="scss">
  .index-box{
    padding:0px!important;
    margin-left:0px;
  }
  .tree-box /deep/ .el-tree-node{
     background: #D8E4DD;
  }
  .tree-box> /deep/ .el-tree>.el-tree-node{
    padding:10px;
  }
  .tree-box> /deep/ .el-tree .is-current{
    background:#fff;
  }
  .table-box{
    padding:15px
  }
  .userModel /deep/ .el-color-picker__trigger{
    width:100%
  }
</style>
